package com.sqx.modules.pay.controller.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.annotation.Login;
import com.sqx.modules.app.dao.UserMoneyDao;
import com.sqx.modules.app.entity.ServiceTime;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.ServiceTimeService;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.bidding.entity.HelpBidding;
import com.sqx.modules.bidding.service.HelpBiddingService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.orders.dao.OrdersDao;
import com.sqx.modules.orders.dao.PayOrderDao;
import com.sqx.modules.orders.entity.Orders;
import com.sqx.modules.orders.entity.PayOrder;
import com.sqx.modules.orders.service.OrdersService;
import com.sqx.modules.pay.config.AliPayConstants;
import com.sqx.modules.pay.dao.PayDetailsDao;
import com.sqx.modules.pay.entity.PayDetails;
import com.sqx.modules.taking.dao.OrderTakingDao;
import com.sqx.modules.taking.entity.OrderTaking;
import com.sqx.modules.taking.service.OrderTakingService;
import com.sqx.modules.task.dao.HelpOrderDao;
import com.sqx.modules.task.entity.HelpOrder;
import com.sqx.modules.task.entity.HelpTake;
import com.sqx.modules.task.service.HelpOrderService;
import com.sqx.modules.task.service.HelpTakeService;
import com.sqx.modules.utils.AmountCalUtils;
import com.sqx.modules.utils.SenInfoCheckUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.sqx.modules.utils.wx.WxPayUtils.getGeneralOrder;

/**
 * 支付宝支付处理--暂不做同步处理、回调方式使用异步
 */
@Slf4j
@RestController
@Api(value = "支付宝支付", tags = {"支付宝支付"})
@RequestMapping("/app/aliPay")
public class AliPayController {

    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private OrdersDao ordersDao;
    @Autowired
    private HelpBiddingService biddingService;
    @Autowired
    private PayOrderDao payOrderDao;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private UserMoneyDao userMoneyDao;
    @Autowired
    private PayDetailsDao payDetailsDao;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private UserService userService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private OrderTakingService orderTakingService;
    @Autowired
    private HelpOrderDao helpOrderDao;
    @Autowired
    private HelpOrderService helpOrderService;
    @Autowired
    private ServiceTimeService serviceTimeService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private HelpTakeService helpTakeService;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @RequestMapping(value = "/notifyApp", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public void notifyApp(HttpServletRequest request, HttpServletResponse response) {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        try {
            log.info("回调成功！！！");
            boolean flag = AlipaySignature.rsaCheckV1(params, commonInfoService.findOne(64).getValue(), AliPayConstants.CHARSET, "RSA2");
            log.info(flag + "回调验证信息");
            if (flag) {
                String tradeStatus = params.get("trade_status");
                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {

                    //支付宝返回的订单编号
                    String outTradeNo = params.get("out_trade_no");
                    log.error(outTradeNo);
                    //支付宝支付单号
                    String tradeNo = params.get("trade_no");
                    PayDetails payDetails = payDetailsDao.selectByOrderId(outTradeNo);
                    if (payDetails.getState() == 0) {
                        payDetailsDao.updateState(payDetails.getId(), 1, sdf.format(new Date()), tradeNo);
                        if (payDetails.getType() == 1) {
                            //设置查询条件
                            QueryWrapper<PayOrder> queryWrapper = new QueryWrapper<>();
                            //根据订单编号去查询订单
                            queryWrapper.eq("orders_no", outTradeNo);
                            //去订单表中查询到该订单
                            PayOrder orders = payOrderDao.selectOne(queryWrapper);
                            //改变订单状态
                            orders.setState(1);
                            orders.setPayWay(4);
                            //设置订单更新时间
                            orders.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                            payOrderDao.updateById(orders);
                            //调用处理接口
                            userMoneyDao.updateMayMoney(1, orders.getUserId(), orders.getMoney());
                            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                            userMoneyDetails.setUserId(orders.getUserId());
                            userMoneyDetails.setTitle("支付宝充值");
                            userMoneyDetails.setContent("支付宝充值:" + orders.getPayMoney());
                            userMoneyDetails.setType(1);
                            userMoneyDetails.setMoney(orders.getMoney());
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            userMoneyDetails.setCreateTime(sdf.format(new Date()));
                            userMoneyDetailsService.save(userMoneyDetails);
                        } else if (payDetails.getType() == 2) {
                            Orders orders = ordersDao.selectOne(new QueryWrapper<Orders>().eq("orders_no", payDetails.getOrderId()));
                            UserEntity userEntity = userService.selectUserById(orders.getUserId());
                            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                            userMoneyDetails.setMoney(orders.getPayMoney());
                            userMoneyDetails.setUserId(orders.getUserId());
                            userMoneyDetails.setContent("支付宝支付订单：" + orders.getOrdersNo());
                            userMoneyDetails.setTitle("下单成功");
                            userMoneyDetails.setType(2);
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                            userMoneyDetailsService.save(userMoneyDetails);
                            MessageInfo messageInfo = new MessageInfo();
                            messageInfo.setContent("订单下单成功：" + orders.getOrdersNo());
                            messageInfo.setTitle("订单通知");
                            messageInfo.setState(String.valueOf(4));
                            messageInfo.setUserName(userEntity.getUserName());
                            messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
                            messageInfo.setCreateAt(simpleDateFormat.format(new Date()));
                            messageInfo.setIsSee("0");
                            messageService.saveBody(messageInfo);
                            if (StringUtil.isNotBlank(userEntity.getClientid())) {
                                userService.pushToSingle(messageInfo.getTitle(), messageInfo.getContent(), userEntity.getClientid());
                            }
                            String userName = userEntity.getUserName();
                            orders.setState("4");
                            orders.setIsRemind(0);
                            orders.setPayWay(3);
                            ordersDao.updateById(orders);
                            OrderTaking byId = orderTakingService.getById(orders.getOrderTakingId());
                            userEntity = userService.selectUserById(byId.getUserId());
                            MessageInfo messageInfos = new MessageInfo();
                            messageInfos.setContent("订单接单成功：" + orders.getOrdersNo());
                            messageInfos.setTitle("订单通知");
                            messageInfos.setState(String.valueOf(6));
                            messageInfos.setUserName(userEntity.getUserName());
                            messageInfos.setUserId(String.valueOf(userEntity.getUserId()));
                            messageInfos.setCreateAt(simpleDateFormat.format(new Date()));
                            messageInfos.setIsSee("0");
                            messageService.saveBody(messageInfos);
                            if (StringUtil.isNotBlank(userEntity.getClientid())) {
                                userService.pushToSingle(messageInfos.getTitle(), messageInfos.getContent(), userEntity.getClientid());
                            }


                            //小程序订阅号消息推送
                            CommonInfo one = commonInfoService.findOne(235);
                            List<String> msgList = new ArrayList<>();
                            msgList.add(orders.getOrdersNo());//订单号
                            if (byId.getGameId().length() > 15) {
                                byId.setGameId(byId.getGameId().substring(0, 15) + "...");
                            }
                            msgList.add(byId.getGameId());//商品名称
                            msgList.add(String.valueOf(orders.getOrderNumber()));//商品数量
                            msgList.add(orders.getCreateTime());//下单时间
                            msgList.add(userName);//客户名称
                            UserEntity shopEntity = userService.getById(orders.getOrderTakingUserId());
                            if (StringUtils.isNotEmpty(shopEntity.getShopOpenId())) {
                                SenInfoCheckUtil.sendShopMsg(shopEntity.getShopOpenId(), one.getValue(), null, msgList, 1);
                            }
                            messageInfo = new MessageInfo();
                            messageInfo.setTitle("订单通知");
                            messageInfo.setState(String.valueOf(10));
                            messageInfo.setIsSee("0");
                            messageService.saveBody(messageInfo);
                        } else if (payDetails.getType() == 4) {
                            ordersService.payBack(payDetails.getRelationId(), payDetails.getOrderType(), 2, BigDecimal.valueOf(payDetails.getMoney()),payDetails.getOrderId());
                            //缴纳保证金
                        } else if (payDetails.getType() == 5) {
                            userMoneyService.safetyMoneyCallback(payDetails);
                        } else if (payDetails.getType() == 6) {
                            Orders orders = ordersDao.selectOne(new QueryWrapper<Orders>().eq("orders_no",payDetails.getOrderId()));
                            userMoneyService.setMember(orders,payDetails.getUserId());
                        } else {
                            HelpOrder helpOrder = JSONObject.parseObject(payDetails.getRemark(), HelpOrder.class);
                            HelpOrder order = helpOrderDao.selectOne(new QueryWrapper<HelpOrder>().eq("order_no", payDetails.getOrderId()));
                            if (helpOrder.getTaskType() == 2) {
                                HelpBidding bidding = biddingService.getById(payDetails.getRelationId());
                                order.setPayWay(3);
                                helpOrderService.choseUserOrder(bidding, order);
                                return;
                            }
                            //如果是竞价则不执行下面的代码
                            UserEntity userEntity = userService.selectUserById(helpOrder.getUserId());
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String date = sdf.format(new Date());
                            helpOrder.setStatus(1);
                            helpOrder.setCreateTime(date);
                            helpOrder.setMoney(helpOrder.getCommission());
                            CommonInfo one = commonInfoService.findOne(120);
                            String value = one.getValue();
                            Double mul = AmountCalUtils.mul(helpOrder.getCommission().doubleValue(), Double.parseDouble(value));
                            BigDecimal sub = AmountCalUtils.sub(helpOrder.getMoney(), BigDecimal.valueOf(mul));
                            helpOrder.setCommission(sub);
                            helpOrder.setPayWay(3);
                            helpOrder.setIsPay(1);
                            helpOrderDao.updateById(helpOrder);
                            if(helpOrder.getTaskType()==4){
                                HelpTake helpTake=new HelpTake();
                                helpTake.setOrderId(helpOrder.getId());
                                helpTake.setUserId(helpOrder.getMasterUserId());
                                helpTakeService.saveBody(helpTake);
                            }
                            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                            userMoneyDetails.setUserId(helpOrder.getUserId());
                            userMoneyDetails.setTitle("万能任务");
                            userMoneyDetails.setContent("万能任务支付宝支付扣款：" + helpOrder.getMoney());
                            userMoneyDetails.setType(2);
                            userMoneyDetails.setMoney(helpOrder.getMoney());
                            userMoneyDetails.setCreateTime(date);
                            userMoneyDetailsService.save(userMoneyDetails);
                            if (userEntity.getClientid() != null) {
                                userService.pushToSingle("派发订单", "您的订单已经派发成功！", userEntity.getClientid());
                            }
                            MessageInfo messageInfo = new MessageInfo();
                            messageInfo.setContent("您的订单已经派发成功！");
                            messageInfo.setTitle("订单通知");
                            messageInfo.setState(String.valueOf(5));
                            messageInfo.setUserName(userEntity.getUserName());
                            messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
                            messageService.saveBody(messageInfo);
                            messageInfo = new MessageInfo();
                            messageInfo.setTitle("订单通知");
                            messageInfo.setState(String.valueOf(11));
                            messageInfo.setIsSee("0");
                            messageService.saveBody(messageInfo);
                        }
                    }
                }

            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            log.info("回调验证失败！！！");
        }
    }

    @Login
    @ApiOperation("支付宝支付充值订单")
    @RequestMapping(value = "/payMoneyOrder", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public Result payMoneyOrder(Long orderId, Integer classify) {
        //通知页面地址
        CommonInfo one = commonInfoService.findOne(19);
        String returnUrl = one.getValue();
        CommonInfo one3 = commonInfoService.findOne(12);
        String name = one3 == null ? "陪玩接单" : one3.getValue();
        String url = one.getValue() + "/sqx_fast/app/aliPay/notifyApp";
        log.info("回调地址:" + url);
        PayOrder orders = payOrderDao.selectById(orderId);
        PayDetails payDetails = payDetailsDao.selectByOrderId(orders.getOrdersNo());
        if (payDetails == null) {
            payDetails = new PayDetails();
            payDetails.setState(0);
            payDetails.setCreateTime(sdf.format(new Date()));
            payDetails.setOrderId(orders.getOrdersNo());
            payDetails.setUserId(orders.getUserId());
            payDetails.setMoney(orders.getPayMoney().doubleValue());
            if (classify == 1) {
                payDetails.setClassify(4);
            } else {
                payDetails.setClassify(5);
            }
            payDetails.setType(1);
            payDetailsDao.insert(payDetails);
        }
        if (classify == 1) {
            return payApp(name, orders.getOrdersNo(), orders.getPayMoney().doubleValue());
        }
        return payH5(name, orders.getOrdersNo(), orders.getPayMoney().doubleValue(), returnUrl);
    }


    @Login
    @ApiOperation("支付宝补费")
    @RequestMapping(value = "/payMoneyRepairFee", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public Result payMoneyRepairFee(@RequestAttribute("userId") Long userId, Long ordersId, BigDecimal money, Integer payType, Integer orderType) {
        //通知页面地址
        CommonInfo one = commonInfoService.findOne(19);
        String returnUrl = one.getValue();
        CommonInfo one3 = commonInfoService.findOne(12);
        String name = one3 == null ? "陪玩接单" : one3.getValue();
        String url = one.getValue() + "/sqx_fast/app/aliPay/notifyApp";
        log.info("回调地址:" + url);

        PayDetails payDetails = new PayDetails();
        payDetails.setState(0);
        payDetails.setCreateTime(sdf.format(new Date()));
        payDetails.setOrderId(getGeneralOrder());
        payDetails.setUserId(userId);
        payDetails.setMoney(money.doubleValue());
        payDetails.setClassify(payType);
        payDetails.setType(4);
        payDetails.setOrderType(orderType);
        payDetails.setRelationId(ordersId);
        payDetailsDao.insert(payDetails);

        if (payType == 4) {
            return payApp(name, payDetails.getOrderId(), payDetails.getMoney());
        }
        return payH5(name, payDetails.getOrderId(), payDetails.getMoney(), returnUrl);
    }

    @Login
    @ApiOperation("支付宝支付家政订单")
    @RequestMapping(value = "/payOrder", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public Result payOrder(Long orderId, Integer classify) {
        //通知页面地址
        CommonInfo one = commonInfoService.findOne(19);
        String returnUrl = one.getValue();
        CommonInfo one3 = commonInfoService.findOne(12);
        String name = one3 == null ? "陪玩接单" : one3.getValue();
        String url = one.getValue() + "/sqx_fast/app/aliPay/notifyApp";
        log.info("回调地址:" + url);
        Orders orders = ordersDao.selectById(orderId);
        if (orders == null) {
            return Result.error("订单生成失败，请重新下单！");
        }
        OrderTaking orderTaking = orderTakingService.getById(orders.getOrderTakingId());
        Integer counts = ordersDao.selectCount(new QueryWrapper<Orders>().in("state", 1, 2, 4).eq("order_taking_user_id", orderTaking.getUserId()).eq("order_taking_id", orderTaking.getId()).eq("start_time", orders.getStartTime()));
        ServiceTime serviceTime = serviceTimeService.getById(orders.getServiceTimeId());
        if (serviceTime.getNum() <= counts) {
            return Result.error("当前时段预约已满，请您更换其他时间段！");
        }

        PayDetails payDetails = payDetailsDao.selectByOrderId(orders.getOrdersNo());
        if (payDetails == null) {
            payDetails = new PayDetails();
            payDetails.setState(0);
            payDetails.setCreateTime(sdf.format(new Date()));
            payDetails.setOrderId(orders.getOrdersNo());
            payDetails.setUserId(orders.getUserId());
            payDetails.setMoney(orders.getPayMoney().doubleValue());
            if (classify == 1) {
                payDetails.setClassify(4);
            } else {
                payDetails.setClassify(5);
            }
            payDetails.setType(2);
            payDetailsDao.insert(payDetails);
        }
        if (classify == 1) {
            return payApp(name, orders.getOrdersNo(), orders.getPayMoney().doubleValue());
        }
        return payH5(name, orders.getOrdersNo(), orders.getPayMoney().doubleValue(), returnUrl);
    }

    @Login
    @ApiOperation("支付宝支付万能订单")
    @RequestMapping(value = "/payHelpOrder", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public Result payHelpOrder(Long relationId, Long orderId, Integer classify, @RequestAttribute Long userId) {
        HelpOrder helpOrder = helpOrderDao.selectById(orderId);
        if (relationId != null) {
            HelpBidding bidding = biddingService.getById(relationId);
            helpOrder.setRelationId(bidding.getBiddingId());
            helpOrder.setCommission(bidding.getOfferMoney());
        }
        //通知页面地址
        CommonInfo one = commonInfoService.findOne(19);
        String returnUrl = one.getValue();
        CommonInfo one3 = commonInfoService.findOne(12);
        String name = one3 == null ? "陪玩接单" : one3.getValue();
        String url = one.getValue() + "/sqx_fast/app/aliPay/notifyApp";
        log.info("回调地址:" + url);
        helpOrder.setUserId(userId);
        if (helpOrder.getCommission().doubleValue() <= 0) {
            return Result.error("金额必须大于0");
        }
        BigDecimal money=helpOrder.getMoney();
        if(relationId!=null){
            money=helpOrder.getCommission();
        }
        helpOrder.setOrderNo(getGeneralOrder());
        PayDetails payDetails = payDetailsDao.selectByOrderId(helpOrder.getOrderNo());
        if (payDetails == null) {
            payDetails = new PayDetails();
            payDetails.setState(0);
            payDetails.setCreateTime(sdf.format(new Date()));
            payDetails.setOrderId(helpOrder.getOrderNo());
            payDetails.setUserId(helpOrder.getUserId());
            payDetails.setMoney(money.doubleValue());
            if (classify == 1) {
                payDetails.setClassify(4);
            } else {
                payDetails.setClassify(5);
            }
            payDetails.setType(3);
            payDetails.setRemark(JSON.toJSONString(helpOrder));
            if (helpOrder.getRelationId() != null) {
                payDetails.setRelationId(helpOrder.getRelationId());
            }
            payDetailsDao.insert(payDetails);
        }

        helpOrderDao.updateById(helpOrder);
        if (classify == 2) {
            return payApp(name, helpOrder.getOrderNo(), money.doubleValue());
        }
        return payH5(name, helpOrder.getOrderNo(), money.doubleValue(), returnUrl);
    }

    @Login
    @ApiOperation("缴纳保证金")
    @RequestMapping(value = "/paySafetyMoney", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public Result wxPaySafetyMoney(@RequestAttribute Long userId, Integer classify, BigDecimal money,Integer userType) {
        //通知页面地址
        String returnUrl;
        if(userType==2){
            CommonInfo one = commonInfoService.findOne(306);
            returnUrl = one.getValue();
        }else{
            CommonInfo one = commonInfoService.findOne(305);
            returnUrl = one.getValue();
        }
        CommonInfo one = commonInfoService.findOne(19);
        CommonInfo one3 = commonInfoService.findOne(12);
        String name = one3 == null ? "家政服务" : one3.getValue();
        String url = one.getValue() + "/sqx_fast/app/aliPay/notifyApp";
        log.info("回调地址:" + url);
        CommonInfo safetyMoneyCommonInfo = commonInfoService.findOne(616);
        UserEntity userEntity = userService.selectUserById(userId);
        UserMoney userMoney = userMoneyDao.selectOne(new QueryWrapper<UserMoney>().eq("user_id", userEntity.getUserId()));
        BigDecimal safetyMoney = new BigDecimal(safetyMoneyCommonInfo.getValue());
        if (userMoney.getSafetyMoney().compareTo(safetyMoney) < 0) {
            String outTradeNo = getGeneralOrder();
            PayDetails payDetails = new PayDetails();
            payDetails.setState(0);
            payDetails.setCreateTime(sdf.format(new Date()));
            payDetails.setOrderId(outTradeNo);
            payDetails.setUserId(userId);
            payDetails.setMoney(money.doubleValue());
            payDetails.setClassify(classify);
            payDetails.setType(5);
            payDetailsDao.insert(payDetails);
            if (classify == 4) {
                return payApp(name, outTradeNo, money.doubleValue());
            }
            return payH5(name, outTradeNo, money.doubleValue(), returnUrl);
        } else {
            return Result.error("你已缴纳足额保证金");
        }
    }


    @Login
    @ApiOperation("缴纳保证金")
    @RequestMapping(value = "/payMember", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public Result payMember(Long ordersId,Integer classify) {
        //通知页面地址
        CommonInfo one = commonInfoService.findOne(19);
        String returnUrl = one.getValue();
        CommonInfo one3 = commonInfoService.findOne(12);
        String name = one3.getValue();
        String url = one.getValue() + "/sqx_fast/app/aliPay/notifyApp";
        log.info("回调地址:" + url);
        Orders orders = ordersDao.selectOne(new QueryWrapper<Orders>().eq("orders_id", ordersId));
        if (orders == null) {
            return Result.error("订单生成失败，请重新下单！");
        }
        PayDetails payDetails = payDetailsDao.selectByOrderId(orders.getOrdersNo());
        if (payDetails == null) {
            payDetails = new PayDetails();
            payDetails.setState(0);
            payDetails.setCreateTime(sdf.format(new Date()));
            payDetails.setOrderId(orders.getOrdersNo());
            payDetails.setUserId(orders.getUserId());
            payDetails.setMoney(orders.getPayMoney().doubleValue());
            payDetails.setClassify(classify);
            payDetails.setType(6);
            payDetailsDao.insert(payDetails);
        }
        if (classify == 4) {
            return payApp(name, payDetails.getOrderId(), payDetails.getMoney());
        }
        return payH5(name, payDetails.getOrderId(), payDetails.getMoney(), returnUrl);
    }

    public Result payApp(String name, String generalOrder, Double money) {
        CommonInfo one = commonInfoService.findOne(19);
        String url = one.getValue() + "/sqx_fast/app/aliPay/notifyApp";
        String result = "";
        CommonInfo payWay = commonInfoService.findOne(258);
        try {
            if ("1".equals(payWay.getValue())) {
                //构造client
                CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
                //设置网关地址
                certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
                //设置应用Id
                certAlipayRequest.setAppId(commonInfoService.findOne(63).getValue());
                //设置应用私钥
                certAlipayRequest.setPrivateKey(commonInfoService.findOne(65).getValue());
                //设置请求格式，固定值json
                certAlipayRequest.setFormat("json");
                //设置字符集
                certAlipayRequest.setCharset(AliPayConstants.CHARSET);
                //设置签名类型
                certAlipayRequest.setSignType(AliPayConstants.SIGNTYPE);
                CommonInfo urls = commonInfoService.findOne(259);
                certAlipayRequest.setCertPath(urls.getValue() + "/appCertPublicKey.crt"); //应用公钥证书路径（app_cert_path 文件绝对路径）
                certAlipayRequest.setAlipayPublicCertPath(urls.getValue() + "/alipayCertPublicKey_RSA2.crt"); //支付宝公钥证书文件路径（alipay_cert_path 文件绝对路径）
                certAlipayRequest.setRootCertPath(urls.getValue() + "/alipayRootCert.crt");  //支付宝CA根证书文件路径（alipay_root_cert_path 文件绝对路径）
                //构造client
                AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);

                //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
                AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
                //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
                AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
                model.setBody(name);
                model.setSubject(name);
                model.setOutTradeNo(generalOrder);
                model.setTimeoutExpress("30m");
                model.setTotalAmount(money + "");
                model.setProductCode("QUICK_MSECURITY_PAY");
                request.setBizModel(model);
                request.setNotifyUrl(url);
                //这里和普通的接口调用不同，使用的是sdkExecute
                AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
                if (response.isSuccess()) {
                    result = response.getBody();
                } else {
                    return Result.error("获取订单失败！");
                }
                return Result.success().put("data", result);
            } else {
                //实例化客户端
                AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", commonInfoService.findOne(63).getValue(), commonInfoService.findOne(65).getValue(), "json", AliPayConstants.CHARSET, commonInfoService.findOne(64).getValue(), "RSA2");
                //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
                AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
                //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
                AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
                model.setBody(name);
                model.setSubject(name);
                model.setOutTradeNo(generalOrder);
                model.setTimeoutExpress("30m");
                model.setTotalAmount(String.valueOf(money));
                model.setProductCode("QUICK_MSECURITY_PAY");
                request.setBizModel(model);
                request.setNotifyUrl(url);
                AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
                if (response.isSuccess()) {
                    result = response.getBody();
                } else {
                    return Result.error("获取订单失败！");
                }
                return Result.success().put("data", result);
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return Result.error(-100, "获取订单失败！");
    }

    public Result payH5(String name, String generalOrder, Double money, String returnUrl) {
        CommonInfo payWay = commonInfoService.findOne(258);
        CommonInfo one = commonInfoService.findOne(19);
        String url = one.getValue() + "/sqx_fast/app/aliPay/notifyApp";
        try {
            if ("1".equals(payWay.getValue())) {
                //构造client
                CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
                //设置网关地址
                certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
                //设置应用Id
                certAlipayRequest.setAppId(commonInfoService.findOne(63).getValue());
                //设置应用私钥
                certAlipayRequest.setPrivateKey(commonInfoService.findOne(65).getValue());
                //设置请求格式，固定值json
                certAlipayRequest.setFormat("json");
                //设置字符集
                certAlipayRequest.setCharset(AliPayConstants.CHARSET);
                //设置签名类型
                certAlipayRequest.setSignType(AliPayConstants.SIGNTYPE);
                CommonInfo urls = commonInfoService.findOne(259);
                certAlipayRequest.setCertPath(urls.getValue() + "/appCertPublicKey.crt"); //应用公钥证书路径（app_cert_path 文件绝对路径）
                certAlipayRequest.setAlipayPublicCertPath(urls.getValue() + "/alipayCertPublicKey_RSA2.crt"); //支付宝公钥证书文件路径（alipay_cert_path 文件绝对路径）
                certAlipayRequest.setRootCertPath(urls.getValue() + "/alipayRootCert.crt");  //支付宝CA根证书文件路径（alipay_root_cert_path 文件绝对路径）
                //构造client
                AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
                AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
                JSONObject order = new JSONObject();
                order.put("out_trade_no", generalOrder); //订单号
                order.put("subject", name); //商品标题
                order.put("product_code", "QUICK_WAP_WAY");
                order.put("body", name);//商品名称
                order.put("total_amount", money + ""); //金额
                alipayRequest.setBizContent(order.toString());
                alipayRequest.setNotifyUrl(url); //在公共参数中设置回跳和通知地址
                alipayRequest.setReturnUrl(returnUrl); //线上通知页面地址
                String result = alipayClient.pageExecute(alipayRequest).getBody();
                return Result.success().put("data", result);
            } else {
                AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", commonInfoService.findOne(63).getValue(), commonInfoService.findOne(65).getValue(), "json", AliPayConstants.CHARSET, commonInfoService.findOne(64).getValue(), "RSA2");
                AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
                JSONObject order = new JSONObject();
                order.put("out_trade_no", generalOrder); //订单号
                order.put("subject", name); //商品标题
                order.put("product_code", "QUICK_WAP_WAY");
                order.put("body", name);//商品名称
                order.put("total_amount", money); //金额
                alipayRequest.setBizContent(order.toString());
                //在公共参数中设置回跳和通知地址
                alipayRequest.setNotifyUrl(url);
                //通知页面地址
                alipayRequest.setReturnUrl(returnUrl);
                String form = alipayClient.pageExecute(alipayRequest).getBody();
                return Result.success().put("data", form);
            }
        } catch (AlipayApiException e) {
            log.error("CreatPayOrderForH5", e);
        }
        return Result.error("获取订单信息错误！");
    }


    public String getGeneralOrder() {
        Date date = new Date();
        String newString = String.format("%0" + 4 + "d", (int) ((Math.random() * 9 + 1) * 1000));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = sdf.format(date);
        return format + newString;
    }


    /**
     * 说明： 支付宝订单退款
     *
     * @return 公共返回参数 code,msg,   响应参数实例: https://docs.open.alipay.com/api_1/alipay.trade.refund
     */
    public String alipayRefund(String ordersNo, BigDecimal money) {
        PayDetails payDetails = payDetailsDao.selectByOrderId(ordersNo);
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", commonInfoService.findOne(63).getValue(), commonInfoService.findOne(65).getValue(), "json", AliPayConstants.CHARSET, commonInfoService.findOne(64).getValue(), "RSA2");
        AlipayTradeRefundRequest alipay_request = new AlipayTradeRefundRequest();
        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
        model.setOutTradeNo(payDetails.getOrderId());//订单编号
        model.setTradeNo(payDetails.getTradeNo());//支付宝订单交易号
        model.setRefundAmount(money.toString());//退款金额 不得大于订单金额
        model.setRefundReason("服务退款");//退款说明
        model.setOutRequestNo(getGeneralOrder());//标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传。
        alipay_request.setBizModel(model);
        try {
            AlipayTradeRefundResponse alipay_response = alipayClient.execute(alipay_request);
            String alipayRefundStr = alipay_response.getBody();
            log.info(alipayRefundStr);
            return alipayRefundStr;
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }


}
